package com.cmcc.passenger.ui.main

//import org.greenrobot.eventbus.EventBus
//import org.greenrobot.eventbus.Subscribe
//import org.greenrobot.eventbus.ThreadMode

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.Color
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Looper
import android.provider.Settings
import android.text.TextUtils
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import cn.qqtheme.framework.picker.DateTimePicker
import cn.qqtheme.framework.popup.BasicPopup
import cn.qqtheme.framework.util.ConvertUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.passenger.AppManager
import com.cmcc.passenger.R
import com.cmcc.passenger.config.AppConfig
import com.cmcc.passenger.config.IntentKeys
import com.cmcc.passenger.config.PassPath
import com.cmcc.passenger.data.entity.request.Coordinates
import com.cmcc.passenger.data.entity.response.*
import com.cmcc.passenger.databinding.ActivityHomeBinding
import com.cmcc.passenger.service.OrderReceiver
import com.cmcc.passenger.service.OrderStateChangeListener
import com.cmcc.passenger.ui.base.BasicActivity
import com.cmcc.passenger.ui.fragment.AppAlertDialog
import com.cmcc.passenger.ui.fragment.AppBlackAlertDialog
import com.cmcc.passenger.ui.fragment.AppProgressDialog
import com.cmcc.passenger.ui.onorder.OnOrderActivity
import com.cmcc.passenger.ui.order.OrderDetailActivity
import com.cmcc.passenger.util.LocationUtil
import com.cmcc.shared.ActivityController
import com.cmcc.shared.SdkManager
import com.cmcc.shared.SdkManager.LANGUAGE_ENG
import com.cmcc.shared.config.SharedConfig.PASS_ORDER_COMPLEIE
import com.cmcc.shared.config.SharedConfig.PASS_ORDER_DRIVER_COME
import com.cmcc.shared.config.SharedConfig.PASS_ORDER_RECEIVED
import com.cmcc.shared.config.SharedConfig.PASS_ORDER_REFUSE
import com.cmcc.shared.config.SharedConfig.PREFS_FILE_NAME
import com.cmcc.shared.config.SharedConfig.REFUSAL_ORDER
import com.cmcc.shared.model.AppResponse
import com.cmcc.shared.utils.L
import com.cmcc.shared.utils.clickWithTrigger
import com.cmcc.shared.utils.isOPenGps
import com.cmcc.shared.utils.showToast
import com.cmcc.shared.viewModel.SharedViewModel
import com.google.android.gms.location.*
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.*
import com.google.android.libraries.places.api.Places
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.api.net.FetchPlaceRequest
import com.google.android.libraries.places.api.net.PlacesClient
import com.google.maps.android.PolyUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.DecimalFormat
import java.util.*

@Route(path = PassPath.PASS_MAIN)
class MainActivity : BasicActivity(), OnMapReadyCallback, OrderStateChangeListener {


    /**
     * 谷歌地图对象实例
     */
    private lateinit var mMap: GoogleMap
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var locationRequest: LocationRequest
    private lateinit var locationCallback: LocationCallback
    private var orderRequest: OrderRecord? = null
    private lateinit var mainBinding: ActivityHomeBinding
    private var mapFragment: SupportMapFragment? = null
    private lateinit var mGeocoder: Geocoder
    private lateinit var viewModel: CallCarViewModel
    private lateinit var placesClient: PlacesClient
    private var alertDialog: AppAlertDialog? = null
    private var progressDialog: AppProgressDialog? = null
    private lateinit var appViewModel: SharedViewModel
    private val sp by lazy {
        getSharedPreferences(PREFS_FILE_NAME, Activity.MODE_PRIVATE)
    }


    /**
     * 行程距离，默认0km
     */
    private var distance: String = "0km"

    /**
     * 行程所需时间
     */
    private var duration: String = "0min"
    private var distanceValue: Int = 0
    private var durationValue: Int = 0

    private var mLastStartSelectorClickTime: Long = 0
    private var mLastEndSelectorClickTime: Long = 0
    private var mLastMoreSelectorClickTime: Long = 0
    private var mLastMeSelectorClickTime: Long = 0
    private var mLastNextSelectorClickTime: Long = 0
    private val TIME_INTERVAL = 1000L
    private var picker: DateTimePicker? = null
    private var canCall = false
    private var canCall2 = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        getExtra(intent)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        intent?.let { it -> getExtra(it) }
    }

    private fun getExtra(intent: Intent) {
        val bundle: Bundle? = intent.extras
        if (bundle != null) {
            val orderId = bundle.getString("orderId")
            val status = bundle.getInt("status")
            if("7".equals(status)){
                AppManager.finishAll()
            }
            val handleMode = intent?.getStringExtra("handleMode")
            when(handleMode?: sp.getInt("mode", 1)) {
                1 -> {
                    if (!orderId.isNullOrEmpty()) {
                        when (status) {
                            6 -> {
                                ARouter.getInstance().build(PassPath.COMMENT)
                                    .withString("order_id", orderId)
                                    .withBoolean("is_doing", true)
                                    .navigation()
                            }
                            else -> {
                                ARouter.getInstance().build(PassPath.CALL_ORDER_DETAIL)
                                    .withString("order_id", orderId)
                                    .withBoolean("is_doing", bundle.getInt("status") == 6)
                                    .navigation()
                            }
                        }
                    }
                }
                2 -> {
                    if (!orderId.isNullOrEmpty()) {
                        ARouter.getInstance().build(PassPath.CALL_ORDER_DETAIL)
                            .withString("order_id", orderId)
                            .navigation()
                    }
                }
            }
        }
    }

    override fun initialize(savedInstanceState: Bundle?) {
        mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_home)
        viewModel = ViewModelProviders.of(this).get(CallCarViewModel::class.java)
        appViewModel = ViewModelProviders.of(this).get(SharedViewModel::class.java)
        mainBinding.toolbar.title.text = getString(R.string.passenger_call_car_title)
        mainBinding.toolbar.profile.visibility = View.VISIBLE
        mainBinding.viewModel = viewModel
        mainBinding.toolbar.toolbar.setNavigationOnClickListener { finish() }
        mainBinding.locate.clickWithTrigger {
            requestLocationPermission()
        }

        if (!Places.isInitialized()) {
            Places.initialize(applicationContext, getString(R.string.google_maps_key))
        }
        // Create a new Places client instance.
        placesClient = Places.createClient(this)

        orderRequest = OrderRecord()

        mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment?
        mapFragment?.getMapAsync(this)

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        locationRequest = LocationRequest()
        locationRequest.interval =
            UPDATE_INTERVAL//请求时间间隔
        locationRequest.fastestInterval =
            FASTEST_INTERVAL//最快时间间隔
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

        locationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult?) {
                if (locationResult == null) return
                handleLocation(locationResult.lastLocation)
            }
        }
        checkGpsPermission()

        mainBinding.options.tips.setOnTouchListener { _: View, _: MotionEvent ->
            true
        }

        mainBinding.options.optionCarType.setOnClickListener(View.OnClickListener {

            navigateToTripOption()
        })

        mainBinding.options.optionTunnel.setOnClickListener(View.OnClickListener {

            navigateToTripOption()
        })


        mainBinding.options.optionPlatform.setOnClickListener(View.OnClickListener {

            navigateToTripOption()
        })


    }

    override fun initView(savedInstanceState: Bundle?) {
        alertDialog = AppAlertDialog(this)
        progressDialog = AppProgressDialog(this)
        progressDialog?.show()
        viewModel.getTravelList()
        viewModel.getPassengerInfo()
        appViewModel.bookCountDownTimer(role = 1)
        //viewModel.getRemarks()  //已废弃，合并到viewModel.getTravelList()中
        mainBinding.rlTips.setOnClickListener(View.OnClickListener {

            ARouter.getInstance().build(PassPath.ON_ORDER).withString(
                "order_temp_id",
                this.order?.id
            ).navigation()
        })
    }

    override fun initEvent(savedInstanceState: Bundle?) {

        //   EventBus.getDefault().register(this)
        mainBinding.options.tripDateTime.isClickable = false
        mainBinding.options.travelMode.setOnCheckedChangeListener { _, checkedId ->
            run {
                when (checkedId) {
                    R.id.realTimeMode -> {
                        mainBinding.options.tripDateTime.text = getString(R.string.real_time)
                        mainBinding.options.tripDateTime.isClickable = false
                        mainBinding.options.showPicker.visibility = View.INVISIBLE

                        year = 0
                        month = 0
                        day = 0
                        hour = 0
                        minute = 0

                        orderRequest?.type = 1
                        orderRequest?.startTime = ""
                    }
                    R.id.reservationMode -> {
                        mainBinding.options.tripDateTime.text = getString(R.string.reservation_time)
                        mainBinding.options.tripDateTime.isClickable = true
                        mainBinding.options.showPicker.visibility = View.VISIBLE

                        orderRequest?.type = 2
                    }
                }
            }
        }

        mainBinding.options.tripDateTime.setOnClickListener {
            if (year == 0 && month == 0 && day == 0) {
                val nowDate = Date()
                val calendar: Calendar = Calendar.getInstance()
                calendar.time = nowDate
                val year = calendar.get(Calendar.YEAR)
                val month = calendar.get(Calendar.MONTH) + 1
                val day = calendar.get(Calendar.DAY_OF_MONTH)
                val hour = when (orderRequest?.type ?: 1) {
                    1 -> {//实时单
                        calendar.get(Calendar.HOUR_OF_DAY)
                    }
                    2 -> {//预约单
                        calendar.get(Calendar.HOUR_OF_DAY) + 1
                    }
                    else -> {
                        calendar.get(Calendar.HOUR_OF_DAY)
                    }
                }
                val minute = calendar.get(Calendar.MINUTE)
                showPicker(year, month, day, hour, minute)
            } else {
                showPicker(year!!, month!!, day!!, hour!!, minute!!)
            }
        }
    }

    var year: Int? = 0
    var month: Int? = 0
    var day: Int? = 0
    var hour: Int? = 0
    var minute: Int? = 0

    private fun showPicker(year: Int, month: Int, day: Int, hours: Int, minutes: Int) {
        picker = DateTimePicker(this, DateTimePicker.HOUR_24)
        when (SdkManager.getLanguage()) {
            0 -> {
                picker?.setLabel("year", "mon", "day", "hours", "mins")
            }
            1 -> {
                picker?.setLabel("年", "月", "日", "时", "分")
            }
            2 -> {
                picker?.setLabel("年", "月", "日", "時", "分")
            }
        }
        picker?.setDateRangeStart(year, 1, 1)
        picker?.setDateRangeEnd(year + 5, 12, 31)
        picker?.setTimeRangeStart(0, 0)
        picker?.setTimeRangeEnd(23, 59)
        picker?.setTopLineColor(resources.getColor(R.color.passenger_dark_gray))
        picker?.setTextColor(resources.getColor(R.color.passenger_colorAccents))
        picker?.setDividerColor(resources.getColor(R.color.passenger_dark_gray))
        picker?.setLabelTextColor(resources.getColor(R.color.passenger_colorAccents))

        picker?.setCycleDisable(false)
        picker?.setOffset(2)
        picker?.setHeight(398)
        picker?.setContentPadding(16, 8)

        picker?.setSelectedItem(year, month, day, hours, minutes)


        picker?.setHeaderView(makeHeaderView())
        picker?.show()
    }

    private fun makeHeaderView(): View? {
        val topButtonLayout = RelativeLayout(this)
        val height = ConvertUtils.toPx(this, 40f)
        topButtonLayout.layoutParams = RelativeLayout.LayoutParams(
            BasicPopup.MATCH_PARENT,
            height
        )
        topButtonLayout.setBackgroundColor(Color.WHITE)
        topButtonLayout.gravity = Gravity.CENTER_VERTICAL
        var cancelButton = TextView(this)

        val cancelParams = RelativeLayout.LayoutParams(
            BasicPopup.WRAP_CONTENT, BasicPopup.MATCH_PARENT
        )
        cancelParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE)
        cancelParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE)
        cancelButton.setLayoutParams(cancelParams)
        cancelButton.setBackgroundColor(Color.TRANSPARENT)
        cancelButton.setGravity(Gravity.CENTER)
        val padding = ConvertUtils.toPx(this, 15f)
        cancelButton.setPadding(padding, 0, padding, 0)
        cancelButton.text = getString(R.string.cancel)
        cancelButton.setTextColor(
            ConvertUtils.toColorStateList(
                resources.getColor(R.color.passenger_colorAccents),
                resources.getColor(R.color.passenger_colorAccents)
            )
        )
        cancelButton.setOnClickListener(View.OnClickListener {
            picker?.dismiss()
        })
        topButtonLayout.addView(cancelButton)


        val textView = TextView(this)
        val titleParams = RelativeLayout.LayoutParams(
            BasicPopup.WRAP_CONTENT, BasicPopup.WRAP_CONTENT
        )
        val margin = ConvertUtils.toPx(this, 15f)
        titleParams.leftMargin = margin
        titleParams.rightMargin = margin
        titleParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE)
        titleParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE)
        textView.layoutParams = titleParams
        textView.gravity = Gravity.CENTER

        textView.setText(getString(R.string.plz_choose_time))
        textView.setTextColor(resources.getColor(R.color.passenger_colorAccents))

        topButtonLayout.addView(textView)
        var submitButton = TextView(this)
        val submitParams = RelativeLayout.LayoutParams(
            BasicPopup.WRAP_CONTENT, BasicPopup.MATCH_PARENT
        )
        submitParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE)
        submitParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE)
        submitButton.setLayoutParams(submitParams)
        submitButton.setBackgroundColor(Color.TRANSPARENT)
        submitButton.setGravity(Gravity.CENTER)
        submitButton.setPadding(padding, 0, padding, 0)

        submitButton.setText(getString(R.string.save))

        submitButton.setTextColor(
            ConvertUtils.toColorStateList(
                resources.getColor(R.color.passenger_colorAccents),
                resources.getColor(R.color.passenger_colorAccents)
            )
        )


        submitButton.setOnClickListener(View.OnClickListener {
            year = picker?.selectedYear?.toInt()
            month = picker?.selectedMonth?.toInt()
            day = picker?.selectedDay?.toInt()
            hour = picker?.selectedHour?.toInt()
            minute = picker?.selectedMinute?.toInt()

            val nowDate = Date()
            var calendar = Calendar.getInstance()
            calendar.set(year!!, month!! - 1, day!!, hour!!, minute!!)

            canCall = calendar.timeInMillis > nowDate.time + 1000 * 60 * 60
            if (canCall) {
                canCall2 = calendar.timeInMillis < nowDate.time + 1000 * 60 * 60 * 24 * 7
                if (canCall2) {
                    val yearStr = picker?.selectedYear
                    val monthStr = picker?.selectedMonth
                    val dayStr = picker?.selectedDay
                    val hourStr = picker?.selectedHour
                    val minuteStr = picker?.selectedMinute

                    picker?.dismiss()
                    mainBinding.options.tripDateTime.text =
                        "$yearStr-$monthStr-$dayStr $hourStr:$minuteStr"
                    orderRequest?.startTime = "$yearStr-$monthStr-$dayStr $hourStr:$minuteStr:00"
                } else {
                    showToast(this, "出行时间应该晚于当前时间一周以内")
                }
            } else {
                showToast(this, "出行时间应该晚于当前时间1个小时以上")
            }
        })
        topButtonLayout.addView(submitButton)
        return topButtonLayout
    }

    private fun computationFee() {
        if (distanceValue != 0 && durationValue != 0) {
            viewModel.computationFee(
                DecimalFormat("0.00").format(distanceValue / 1000).toDouble(),
                orderRequest?.tunnel?.code ?: "0",
                orderRequest?.carCategory?.code ?: "0"
            )
        }
    }

    /**
     * 初始化观察方法，用于更新数据和界面
     */
    override fun initObserver(savedInstanceState: Bundle?) {
        appViewModel.isShowBookOver.observe(this, Observer {
            if (it.second) {
                alertDialog?.dismiss()
                AppAlertDialog(this).setContent(getString(R.string.book_time_over))
                    .setNavigation(getString(R.string.i_get), null)
                    .setPositive(getString(com.cmcc.shared.R.string.contact_cuservice),
                        View.OnClickListener {
                            val data = Uri.parse("tel:85262325253")
                            val intent = Intent(Intent.ACTION_DIAL, data)
                            startActivity(intent)
                        })
                    .show()
            }
        })

        viewModel.passengerInfo.observe(this, Observer {
            if (it?.headPortraitAddress != null) {
                //先用默认图

                // mainBinding.avatarUrl = it.headPortraitAddress
            }
        })

        viewModel.googleDirection.observe(this, Observer { direction ->
            distance = direction?.distance ?: ""
            duration = direction?.duration ?: ""
            distanceValue = direction?.distanceValue ?: 0
            durationValue = direction?.durationValue ?: 0

            computationFee()
        })

        viewModel.orderFee.observe(this, Observer {


            val amount = it?.totalAmount ?: 0.0

            if (TextUtils.isEmpty(mainBinding.directions.directionEnd.text.toString())) {
                return@Observer
            }
            //暂时去掉
            mainBinding.options.next.text =
                resources.getString(R.string.str_expect) + " HK$ " + amount.plus(
                    orderRequest?.bountyFee?.toDouble() ?: 0.00
                )
        })



        viewModel.directionStartSelector().observe(this, Observer {
            val nowTime = System.currentTimeMillis()
            if (nowTime - mLastStartSelectorClickTime > TIME_INTERVAL) {
                mLastStartSelectorClickTime = nowTime
                navigateToPlaceSearchOrigin()
            }
        })
        viewModel.directionEndSelector().observe(this, Observer {
            val nowTime = System.currentTimeMillis()
            if (nowTime - mLastEndSelectorClickTime > TIME_INTERVAL) {
                mLastEndSelectorClickTime = nowTime
                navigateToPlaceSearchDestination()
            }
        })
        viewModel.createOrder.observe(this, Observer { response ->
            afterCreateOrder(response)
        })
        viewModel.processOrder.observe(this, Observer { order ->
            this.order = order;
//            if(!isSee){
//              return@Observer
//            }
            if (order == null) {
                alertDialog?.dismiss()
            } else {
                when(order.handleMode) {
                    1 -> {
                        if (order.driverCarId.isNullOrBlank()) {

                            if(!isSee){
                                alertDialog?.setContent(getString(R.string.order_on_process_message))
                                    ?.setNavigation(getString(R.string.cancel), View.OnClickListener {
                                        mainBinding.rlTips.visibility = View.VISIBLE;

                                    })
                                    ?.setPositive(getString(R.string.enter), View.OnClickListener {
                                        navigateToOnOrder(order)
                                    })?.show()
                             }


                        } else {
                            if (order.status ?: 0 > 0) {

                                if(isSee){

                                    alertDialog?.setContent(getString(R.string.order_on_process_message))
                                        ?.setNavigation(getString(R.string.cancel), View.OnClickListener {
                                            mainBinding.rlTips.visibility = View.VISIBLE;
                                        })
                                        ?.setPositive(getString(R.string.enter), View.OnClickListener {
                                            navigateToOrderDetail(order)
                                        })?.show()
                                }


                            }
                        }
                    }
                    2 -> {
                        if (order.status ?: 0 > 0) {

                            if(isSee){

                                alertDialog?.setContent(getString(R.string.order_on_process_message))
                                    ?.setNavigation(getString(R.string.cancel), View.OnClickListener {

                                        mainBinding.rlTips.visibility = View.VISIBLE;
                                    })
                                    ?.setPositive(getString(R.string.enter), View.OnClickListener {
                                        navigateToOrderDetail(order)
                                    })?.show()
                            }

                        }else {
                            if(isSee){

                                alertDialog?.setContent(getString(R.string.order_on_process_message))
                                    ?.setNavigation(getString(R.string.cancel), View.OnClickListener {
                                        mainBinding.rlTips.visibility = View.VISIBLE;

                                    })
                                    ?.setPositive(getString(R.string.enter), View.OnClickListener {
                                        navigateToOnOrder(order)
                                    })?.show()
                            }


                        }
                    }
                }

            }
        })
        viewModel.moreOptionSelector().observe(this, Observer {
            val nowTime = System.currentTimeMillis()
            if (nowTime - mLastMoreSelectorClickTime > TIME_INTERVAL) {
                mLastMoreSelectorClickTime = nowTime
                navigateToTripOption()
            }
        })
        viewModel.geoLocation.observe(this, Observer {
            onGeoLocationSuccess(it)
        })
        viewModel.meSelector().observe(this, Observer {
            val nowTime = System.currentTimeMillis()
            if (nowTime - mLastMeSelectorClickTime > TIME_INTERVAL) {
                mLastMeSelectorClickTime = nowTime
                navigateToProfile()
            }
        })

        viewModel.nextStepSelector().observe(this, Observer {
            val nowTime = System.currentTimeMillis()
            if (nowTime - mLastNextSelectorClickTime > TIME_INTERVAL) {
                mLastNextSelectorClickTime = nowTime
                when (orderRequest?.type ?: 1) {
                    1 -> {//实时单
                        onNextStepClick()
                    }
                    2 -> {//预约单
                        val nowDate = Date()
                        var calendar = Calendar.getInstance()
                        calendar.set(year!!, month!! - 1, day!!, hour!!, minute!!)

                        canCall = calendar.timeInMillis >= nowDate.time + 1000 * 60 * 60
                        if (canCall) {
                            canCall2 =
                                calendar.timeInMillis <= nowDate.time + 1000 * 60 * 60 * 24 * 7
                            if (canCall2) {
                                onNextStepClick()
                            } else {
                                showToast(this, "出行时间应该晚于当前时间一周以内")
                            }
                        } else {
                            showToast(this, "出行时间应该晚于当前时间1个小时以上")
                        }
                    }
                }
            }
        })

        viewModel.getTunnel().observe(this, Observer { tunnels ->
            initTunnelView(tunnels)
        })

        viewModel.getCarCategory().observe(this, Observer { carTypes ->
            initCarCategoryView(carTypes)
        })

        viewModel.getStations().observe(this, Observer { stations ->
            initStationView(stations)
        })

        initRoute(intent)
    }

    private fun onGeoLocationSuccess(it: String?) {
        mainBinding.directions.directionStart.text = it
        queryRoute()
    }

    private fun initStationView(stations: List<Station>) {
        if (stations.isNotEmpty()) {
            if (orderRequest?.stationIndex == null) {
                mainBinding.options.optionPlatform.text =
                    getString(R.string.passenger_station_with_colon) + stations[0].name
                orderRequest?.stationIndex = stations[0].id
            } else {
                stations.forEach { station ->
                    if (orderRequest?.stationIndex.equals(station.id)) {
                        val optionPlatform = when (orderRequest?.stationIndex) {
                            null -> getString(R.string.passenger_station_with_colon) + getString(R.string.passenger_any)
                            "0" -> getString(R.string.passenger_station_with_colon) + getString(R.string.passenger_any)
                            else -> getString(R.string.passenger_station_with_colon) + orderRequest?.stationIndex
                        }
                        mainBinding.options.optionPlatform.text = optionPlatform
                    }
                }
            }
        }
    }

    private fun initCarCategoryView(carTypes: List<CarCategory>) {
        if (carTypes.isNotEmpty()) {
            if (orderRequest?.carCategory == null) {
                mainBinding.options.optionCarType.text =
                    getString(R.string.passenger_car_type_with_colon) + carTypes[0].name
                orderRequest?.carCategory = carTypes[0]
            } else {
                carTypes.forEach { carType ->
                    if (orderRequest?.carCategory?.id.equals(carType.id)) {
                        mainBinding.options.optionCarType.text =
                            getString(R.string.passenger_car_type_with_colon) + carType.name
                    }
                }
            }
        }
    }

    private fun initTunnelView(tunnels: List<Tunnel>) {
        progressDialog?.dismiss()
        if (tunnels.isNotEmpty()) {
            if (orderRequest?.tunnel == null) {
                mainBinding.options.optionTunnel.text =
                    getString(R.string.passenger_tunnel_with_colon) + tunnels[0].name
                orderRequest?.tunnel = tunnels[0]
            } else {
                tunnels.forEach { tunnel ->
                    if (orderRequest?.tunnel?.id.equals(tunnel.id)) {
                        mainBinding.options.optionCarType.text =
                            getString(R.string.passenger_tunnel_with_colon) + tunnel.name
                    }
                }
            }
        }
    }

    private fun onNextStepClick() {
        val origin = mainBinding.directions.directionStart.text.toString()
        val destination = mainBinding.directions.directionEnd.text.toString()

        orderRequest?.startAddress = origin
        orderRequest?.endAddress = destination
        if (origin.isNullOrBlank()) {
            alertDialog?.setContent(getString(R.string.plz_choose_direction_origin))
                ?.setNavigation("", null, false)
                ?.setPositive(getString(R.string.make_sure), null)?.show()
            return
        }

        if (destination.isNullOrBlank()) {
            alertDialog?.setContent(getString(R.string.plz_choose_direction_destination))
                ?.setNavigation("", null, false)
                ?.setPositive(getString(R.string.make_sure), null)?.show()
            return
        }

        if (orderRequest?.type == 2 && orderRequest?.startTime.isNullOrBlank()) {
            alertDialog?.setContent(getString(R.string.plz_choose_time))
                ?.setNavigation("", null, false)
                ?.setPositive(getString(R.string.make_sure), null)?.show()
            return
        }

        progressDialog?.show()
        orderRequest?.vehicleTypeCode = orderRequest?.carCategory?.code
        orderRequest?.tunnelCode = orderRequest?.tunnel?.code
        viewModel.createOrder(orderRequest)
    }

    private fun navigateToProfile() {
        ARouter.getInstance().build(PassPath.PROFILE).navigation()
    }

    /**
     * 跳转到地址搜索页面，并通过参数标记为查找出发地
     */
    private fun navigateToPlaceSearchOrigin() {
        ARouter.getInstance().build(PassPath.DIRECTION_SEARCH_MAIN)
            .withInt("request_code", 4)
            .navigation(
                this,
                REQUEST_CODE_DIRECTION_START_CODE
            )
    }

    /**
     * 跳转到地址搜索页面，并通过参数标记为查找目的地。
     */
    private fun navigateToPlaceSearchDestination() {
        ARouter.getInstance().build(PassPath.DIRECTION_SEARCH_MAIN)
            .withInt("request_code", 5)
            .navigation(
                this,
                REQUEST_CODE_DIRECTION_END_CODE
            )
    }

    /**
     * 创建订单的服务器返回处理。
     */
    private fun afterCreateOrder(response: AppResponse<CreateOrderResponse>) {
        progressDialog?.dismiss()
        when (response.code) {
            200 -> {
                sp.edit().putInt("mode", response.data.mode).apply()
                ARouter.getInstance().build(PassPath.ON_ORDER)
//                    .withParcelable(IntentKeys.ORDER_REQUEST, orderRequest)
                    .withString("order_temp_id", response.data.id).navigation()
            }
            400 ->
                viewModel.queryOrderProgress()
            1001, 1003 -> {
                AppBlackAlertDialog(this).setContent(response.msg)
                    .show()
            }
            else ->
                alertDialog?.setContent(getString(R.string.create_order_failed_message))
                    ?.setNavigation("", null, false)
                    ?.setPositive(getString(R.string.make_sure), null)?.show()
        }

    }
    private var  order: OrderRecord?=null;
    /**
     * 提示有未处理的订单
     */
    private fun havingProcessOrder(order: OrderRecord?) {
        if (null != order)
            alertDialog?.setContent(getString(R.string.order_on_process_message))
                ?.setNavigation(getString(R.string.cancel), null)
                ?.setPositive(getString(R.string.enter), View.OnClickListener {
                    if (order.status ?: 0 > 0)
                        navigateToOrderDetail(order)
                    else
                        navigateToOnOrder(order)
                })?.show()
    }

    /**
     * 跳转到{@link OnOrderActivity}
     */
    private fun navigateToOnOrder(order: OrderRecord) {
        ARouter.getInstance().build(PassPath.ON_ORDER).withString(
            "order_temp_id",
            order.id
        ).navigation()
    }

    /**
     * 跳转到{@link OrderDetailActivity}
     */
    private fun navigateToOrderDetail(order: OrderRecord) {
        when(order.handleMode) {
            1 ->
                ARouter.getInstance().build(PassPath.CALL_ORDER_DETAIL)
                    .withString(
                        "order_id", order.id
                    ).navigation()
            2 ->
                ARouter.getInstance().build(PassPath.CALL_ORDER_DETAIL)
                    .withString("order_id", order.id)
                    .navigation()
        }
    }

    /**
     * 跳转到{@link TripOptionActivity}
     */
    private fun navigateToTripOption() {
        AppConfig.response = orderRequest
        ARouter.getInstance().build(PassPath.TRIP_OPTIONS)
            .withString(
                IntentKeys.DIRECTION_ORIGIN,
                mainBinding.directions.directionStart.text.toString()
            )
            .withString(
                IntentKeys.DIRECTION_DESINATION,
                mainBinding.directions.directionEnd.text.toString()
            )
            //.withParcelable(IntentKeys.ORDER_REQUEST, orderRequest)
            .navigation(
                this,
                REQUEST_CODE_TRIP_OPTION
            )
    }

    /**
     * 检查是否开启GPS
     */
    private fun checkGpsPermission() {
        if (!isOPenGps(this)) {
            AppAlertDialog(this).setContent(getString(R.string.app_permission_request_message))
                .setNavigation(getString(R.string.reject), View.OnClickListener { finish() })
                .setPositive(getString(
                    R.string.agree
                ),
                    View.OnClickListener {
                        startActivityForResult(
                            Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),
                            REQUEST_CODE_GPS_CODE
                        )
                    }).show()
        } else {
            mapFragment?.getMapAsync(this)
        }
    }

    /**
     * 获取当前位置的回调方法
     */
    private fun handleLocation(lastLocation: Location) {
        mMap.isMyLocationEnabled = true
        mMap.uiSettings.isRotateGesturesEnabled = false
        mMap.uiSettings.isCompassEnabled = true
        mMap.uiSettings.isMyLocationButtonEnabled = false
        val latLng = LatLng(lastLocation.latitude, lastLocation.longitude)
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18f))

        mMap.setOnCameraIdleListener {
            val lat = mMap.cameraPosition.target.latitude
            val lng = mMap.cameraPosition.target.longitude
            if (orderRequest?.startCoordinates == null)
                orderRequest?.startCoordinates = Coordinates()
            orderRequest?.startCoordinates?.x = lng
            orderRequest?.startCoordinates?.y = lat
            geoCode(lat, lng)
        }

        LocationUtil.getInstance().setCurrentLoc(latLng)

        stopLocationUpdate()
    }

    private fun stopLocationUpdate() {
        fusedLocationClient.removeLocationUpdates(locationCallback)
    }

    /**
     * 地图初始化完成后的回调方法
     */
    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap
        mGeocoder = Geocoder(this, Locale.getDefault())
        mMap.setOnCameraIdleListener {
            val lat = mMap.cameraPosition.target.latitude
            val lng = mMap.cameraPosition.target.longitude
            if (orderRequest?.startCoordinates == null) orderRequest?.startCoordinates =
                Coordinates()
//            if (orderRequest?.endCoordinates == null) orderRequest?.endCoordinates = Coordinates()
            orderRequest?.startCoordinates?.x = lng
            orderRequest?.startCoordinates?.y = lat
//            orderRequest?.endCoordinates?.x = lng
//            orderRequest?.endCoordinates?.y = lat
            geoCode(lat, lng)
        }
        val appointLoc = LocationUtil.getInstance().getCurrentLoc()
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(appointLoc, 18f))
        drawRoutes(googleMap)
        requestLocationPermission()
    }

    /**
     * 将经纬度转化为地址位置
     */
    private fun geoCode(lat: Double, lng: Double) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val result = mGeocoder.getFromLocation(lat, lng, 1)
                if (result.isNotEmpty()) {
                    val buffer = StringBuffer()
                    val language = SdkManager.getLanguage()
                    for (address in result) {
                        if (language == LANGUAGE_ENG) {
                            buffer.append(address.getAddressLine(0).split(",")[0])
                        } else {
                            buffer.append(address.getAddressLine(0).split(" ")[0])
                        }
                    }
                    CoroutineScope(Dispatchers.Main).launch {
                        viewModel.geoLocation.value = buffer.toString()
                    }
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }

        }
    }

    /**
     * 线到谷歌地图绘制路
     */
    private fun drawRoutes(map: GoogleMap) {
        viewModel.direction.observe(this, Observer {
            progressDialog?.dismiss()
            val decodedPath = PolyUtil.decode(it) //来源Google Map Util
            val lineOptions = PolylineOptions()
            lineOptions.addAll(decodedPath) //添加路线
            lineOptions.color(Color.parseColor("#0AC6A2")) //线条设置
            lineOptions.jointType(JointType.ROUND)
            lineOptions.width(15f)
            map.clear()
            map.addPolyline(lineOptions)
            if (decodedPath.size > 2) {
                zoomRoute(map, decodedPath)
                map.addMarker(
                    MarkerOptions().position(decodedPath[0]).icon(
                        BitmapDescriptorFactory.fromResource(
                            R.drawable.ic_start_point
                        )
                    )
                )
                map.addMarker(
                    MarkerOptions().position(decodedPath[decodedPath.size - 1]).icon(
                        BitmapDescriptorFactory.fromResource(R.drawable.ic_end_point)
                    )
                )
                map.setOnCameraIdleListener { }
                mainBinding.centerLocation.visibility = View.GONE
            }
        })

        viewModel.noRouters.observe(this, Observer { noRouter ->
            progressDialog?.dismiss()
            if (noRouter) Toast.makeText(
                this,
                getString(R.string.can_not_find_route),
                Toast.LENGTH_SHORT
            ).show()
        })
    }

    /**
     * Google Play Service的定位权限检查，在一些机型不适用。
     */
    fun checkGpsSettings() {
        val locationRequest = LocationRequest.create()
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        locationRequest.interval = UPDATE_INTERVAL
        locationRequest.fastestInterval =
            FASTEST_INTERVAL
        val builder = LocationSettingsRequest.Builder().addLocationRequest(
            locationRequest
        )
        builder.setAlwaysShow(true)
        val result =
            LocationServices.getSettingsClient(this).checkLocationSettings(builder.build())

        result.addOnSuccessListener {
            Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show()
            mapFragment?.getMapAsync(this)
        }

        result.addOnCanceledListener {
            Toast.makeText(this, "Cancel", Toast.LENGTH_SHORT).show()
        }

    }

    /**
     * 动态请求定位权限
     */
    private fun requestLocationPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            requestLocationService()
            return
        }
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            requestLocationService()
        } else {
            requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
        }
    }

    /**
     * 请求定位服务
     */
    private fun requestLocationService() {
        val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            requestLocationUpdate()
        }
    }

    /**
     * 请求位置更新
     */
    private fun requestLocationUpdate() {
        fusedLocationClient.requestLocationUpdates(
            locationRequest,
            locationCallback,
            Looper.myLooper()
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_CHECK_GPS_SETTINGS) {
            checkGpsPermission()
        } else if (requestCode == REQUEST_CODE_DIRECTION_END_CODE && resultCode == Activity.RESULT_OK) {
            initRoute(data)
//            mainBinding.directions.directionEnd.text = data?.extras?.getString("direction")
//
//            val placeId = data?.extras?.getString("placeId") ?: ""
//            // Specify the fields to return.
//            val placeFields = mutableListOf(Place.Field.ID, Place.Field.LAT_LNG)
//
//            // Construct a request object, passing the place ID and fields array.
//            val request = FetchPlaceRequest.newInstance(placeId, placeFields)
//
//            placesClient.fetchPlace(request).addOnSuccessListener { result ->
//                val place = result.place
//                orderRequest?.endCoordinates = Coordinates()
//                orderRequest?.endCoordinates?.x = place.latLng?.longitude ?: 0.0
//                orderRequest?.endCoordinates?.y = place.latLng?.latitude ?: 0.0
//                queryRoute()
//            }

        } else if (requestCode == REQUEST_CODE_DIRECTION_START_CODE && resultCode == Activity.RESULT_OK) {
            mainBinding.directions.directionStart.text = data?.extras?.getString("direction")
            val placeId = data?.extras?.getString("placeId") ?: ""
            // Specify the fields to return.
            val placeFields = listOf(Place.Field.ID, Place.Field.LAT_LNG)

            // Construct a request object, passing the place ID and fields array.
            val request = FetchPlaceRequest.newInstance(placeId, placeFields)

            placesClient.fetchPlace(request).addOnSuccessListener { result ->

                val place = result.place
                orderRequest?.startCoordinates = Coordinates()
                orderRequest?.startCoordinates?.x = place.latLng?.longitude ?: 0.0
                orderRequest?.startCoordinates?.y = place.latLng?.latitude ?: 0.0
                queryRoute()
            }

        } else if (requestCode == REQUEST_CODE_TRIP_OPTION && resultCode == Activity.RESULT_OK) {
            // orderRequest = data?.extras?.getParcelable(IntentKeys.ORDER_REQUEST)
            orderRequest = AppConfig.response!!
//            var free = data?.getStringExtra(IntentKeys.FREE)?.toInt()
//
//            orderRequest?.bountyFee = free.toString()

            val optionCarType = orderRequest?.carCategory?.name
            val optionTunnel = orderRequest?.tunnel?.name
            val optionPlatform = when (orderRequest?.stationIndex) {
                null -> getString(R.string.passenger_any)
                "0" -> getString(R.string.passenger_any)
                else -> orderRequest?.stationIndex
            }
            val optionRemark = orderRequest?.remark

            if (optionCarType != null) {
                mainBinding.options.optionCarType.text =
                    getString(R.string.passenger_car_type_with_colon) + optionCarType
                mainBinding.options.optionCarType.visibility = View.VISIBLE
            }
            if (optionTunnel != null) {
                mainBinding.options.optionTunnel.text =
                    getString(R.string.passenger_tunnel_with_colon) + optionTunnel
                mainBinding.options.optionTunnel.visibility = View.VISIBLE
            }
            if (optionPlatform != null) {
                mainBinding.options.optionPlatform.text =
                    getString(R.string.passenger_station_with_colon) + optionPlatform
                mainBinding.options.optionPlatform.visibility = View.VISIBLE
            } else {
                mainBinding.options.optionPlatform.visibility = View.GONE
            }

            mainBinding.options.remarkContent.text = optionRemark

            computationFee()
        }
    }

    private fun initRoute(intent: Intent?) {
        val bundle: Bundle? = intent?.extras
        if (bundle != null) {
            mainBinding.directions.directionEnd.text = bundle.getString("direction")

            val placeId = bundle.getString("placeId") ?: ""
            // Specify the fields to return.
            val placeFields = mutableListOf(Place.Field.ID, Place.Field.LAT_LNG)

            // Construct a request object, passing the place ID and fields array.
            val request = FetchPlaceRequest.newInstance(placeId, placeFields)

            placesClient.fetchPlace(request).addOnSuccessListener { result ->
                val place = result.place
                orderRequest?.endCoordinates = Coordinates()
                orderRequest?.endCoordinates?.x = place.latLng?.longitude ?: 0.0
                orderRequest?.endCoordinates?.y = place.latLng?.latitude ?: 0.0
                queryRoute()
            }
        }
    }

    /**
     * 请求路线
     */
    private fun queryRoute() {
        val origin = mainBinding.directions.directionStart.text
        val destination = mainBinding.directions.directionEnd.text
        if (!origin.isNullOrEmpty() && !destination.isNullOrEmpty()) {
            progressDialog?.show()
            viewModel.getDirection(
                orderRequest?.startCoordinates?.y.toString() + "," + orderRequest?.startCoordinates?.x,
                orderRequest?.endCoordinates?.y.toString() + "," + orderRequest?.endCoordinates?.x
            )
        }
    }

    /**
     * Zooms a Route (given a List of LalLng) at the greatest possible zoom level.
     *
     * @param googleMap: instance of GoogleMap
     * @param lstLatLngRoute: list of LatLng forming Route
     */
    private fun zoomRoute(googleMap: GoogleMap?, lstLatLngRoute: List<LatLng>?) {

        if (googleMap == null || lstLatLngRoute == null || lstLatLngRoute.isEmpty()) return

        val boundsBuilder = LatLngBounds.Builder()
        for (latLngPoint in lstLatLngRoute)
            boundsBuilder.include(latLngPoint)

        val routePadding = 100
        val latLngBounds = boundsBuilder.build()

        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, routePadding))
    }

    /**
     * 权限请求回调方法
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            requestLocationUpdate()
        }
    }

    companion object {
        /**
         * 出发地
         */
        const val REQUEST_CODE_DIRECTION_START_CODE = 0x001

        /**
         * 目的地
         */
        const val REQUEST_CODE_DIRECTION_END_CODE = 0x002

        /**
         * 打开GPS
         */
        const val REQUEST_CODE_GPS_CODE = 0x003

        /**
         * 更多出行要求
         */
        const val REQUEST_CODE_TRIP_OPTION = 0x004

        /**
         * 检查GPS设置
         */
        const val REQUEST_CODE_CHECK_GPS_SETTINGS = 0x005


        /**
         * 定位更新时间间隔
         */
        const val UPDATE_INTERVAL = 1 * 1000L  /* 10 secs */

        /**
         * 定位最快更新时间间隔
         */
        const val FASTEST_INTERVAL = 1500L /* 1.5 sec */
    }


//    override fun onPause(){
//        unregisterReceiver(receiver);
//        super.onPause()
//    }
    private var isSee:Boolean = false;
    private var receiver: OrderReceiver? = null
    override fun onResume() {
        isSee = true;
        if (receiver == null) {
            receiver = OrderReceiver()
        }

        receiver?.setOrderStateChangeListener(this)
        val filter = IntentFilter(PASS_ORDER_RECEIVED)
        val filter2 = IntentFilter(PASS_ORDER_DRIVER_COME)
        val filter3 = IntentFilter(PASS_ORDER_COMPLEIE)
        val filter4 = IntentFilter(REFUSAL_ORDER)
        val filter5 = IntentFilter(PASS_ORDER_REFUSE)
        //注册BroadcastReceiver
        registerReceiver(receiver, filter);
        registerReceiver(receiver, filter2);
        registerReceiver(receiver, filter3);
        registerReceiver(receiver, filter4);
        registerReceiver(receiver, filter5);
        if (isRefresh) {
            viewModel.queryOrderProgress()
        }
        isRefresh = true;
        super.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
        //  EventBus.getDefault().unregister(this)
    }

    private var isRefresh: Boolean = true;
    override fun stateChange(intent: Intent?) {
        val action = intent?.action
        val orderId = intent?.getStringExtra("orderId")
        val status = intent?.getStringExtra("status")
        if("7".equals(status)){
           AppManager.finishAll()
            return
        }

        val handleMode = intent?.getStringExtra("handleMode")
        when(handleMode?: sp.getInt("mode", 1)) {
            1 -> {
                //有司机抢单，刷新乘客界面
                if (action.equals(PASS_ORDER_RECEIVED)) {
                    //关闭订单界面 会重新回到 首页 会调用onResum方法，这个时候会去刷新 是否有新的订单，这里是错误的
                    //这个时候 不用给去刷新，
                    isRefresh = false;
                    if (ActivityController.getInstance().currentActivity() is OnOrderActivity) {
                        ActivityController.getInstance()
                            .finishSingleActivity(ActivityController.getInstance().currentActivity())
                    }
                    ARouter.getInstance().build(PassPath.CALL_ORDER_DETAIL)
                        .withString("order_id", orderId)
                        .withBoolean("is_doing", false)
                        .navigation()
                }
                //司机已到达，刷新乘客界面
                else if (action.equals(PASS_ORDER_DRIVER_COME)) {
                    ARouter.getInstance().build(PassPath.CALL_ORDER_DETAIL)
                        .withString("order_id", orderId)
                        .withBoolean("is_doing", false)
                        .navigation()

                    //关闭等待界面
                    ActivityController.getInstance()
                        .finishSingleActivityByClass(OnOrderActivity::class.java);


                }
                //已完成，刷新乘客界面 (去评价界面)
                else if (action.equals(PASS_ORDER_COMPLEIE)) {
                    //            alertDialog?.dismiss()
                    flushPassengerMain()
                    ARouter.getInstance().build(PassPath.COMMENT)
                        .withString("order_id", orderId)
                        .withBoolean("is_doing", true)
                        .navigation()
                    //关闭等待界面
                    ActivityController.getInstance()
                        .finishSingleActivityByClass(OnOrderActivity::class.java);
                    //关闭订单详情界面
                    ActivityController.getInstance()
                        .finishSingleActivityByClass(OrderDetailActivity::class.java);

                } else if (action.equals(REFUSAL_ORDER)) {
                    alertDialog()

                    val currentActivity = ActivityController.getInstance().currentActivity()
                    if (currentActivity is OnOrderActivity || currentActivity is OrderDetailActivity) {
                        ActivityController.getInstance()
                            .finishSingleActivity(currentActivity)
                    }
                }
            }
            2 -> {
                flushPassengerMain()
                if (ActivityController.getInstance().currentActivity() is OnOrderActivity) {
                    ActivityController.getInstance()
                        .finishSingleActivity(ActivityController.getInstance().currentActivity())
                }
                ARouter.getInstance().build(PassPath.CALL_ORDER_DETAIL)
                    .withString("order_id", orderId)
                    .navigation()
            }
        }

    }

    /**
     * 刷新首页的数据
     */
    private fun flushPassengerMain() {
        alertDialog?.dismiss()
//        mainBinding.directions.directionStart.text = ""
        mainBinding.directions.directionEnd.text = ""
        mMap.clear()
        requestLocationPermission()
        orderRequest = OrderRecord()
        viewModel.getTravelList()
        mainBinding.centerLocation.visibility = View.VISIBLE


        mainBinding.options.optionCarType.text =
            getString(R.string.passenger_car_type_with_colon) + getString(R.string.passenger_any)

        mainBinding.options.optionTunnel.text =
            getString(R.string.passenger_tunnel_with_colon) + getString(R.string.passenger_any)

        mainBinding.options.optionPlatform.text =
            getString(R.string.passenger_station_with_colon) + getString(R.string.passenger_any)


        mainBinding.options.remarkContent.text = ""

        mainBinding.options.tripDateTime.text = getString(R.string.real_time)
        mainBinding.options.tripDateTime.isClickable = false
        mainBinding.options.showPicker.visibility = View.INVISIBLE

        year = 0
        month = 0
        day = 0
        hour = 0
        minute = 0

        orderRequest?.type = 1
        orderRequest?.startTime = ""

        mainBinding.options.next.text =
            resources.getString(R.string.passenger_call_car)



        mainBinding.options.realTimeMode.isChecked = true

        mainBinding.options.reservationMode.isChecked = false
        //重新定位
        requestLocationService()


    }

    private fun alertDialog() {
        alertDialog?.setContent(getString(R.string.plz_recall_reason_for_driver_cancel))
            ?.setNavigation(getString(R.string.cancel), null, true)
            ?.setPositive(getString(R.string.confirm), null)?.show()
    }

//    /**
//     * //监听外来是否要恢复按钮
//     *
//     * @param event
//     */
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    fun onEvent(event: MessageEvent) { /* Do something */
//        if (event != null && event.passenMainEvent != null) {
//            if (event.passenMainEvent.code == 200) {
//               flushPassengerMain()
//
//            }
//        }
//
//    }

    override fun onPause() {
        super.onPause()
        mainBinding.rlTips.visibility = View.GONE;
        isSee = false;
    }

}
